import { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Card, Typography } from 'antd';
import axios from 'axios';
import { AudioOutlined, CustomerServiceOutlined, LeftOutlined } from '@ant-design/icons';
import './thirdPage.css';
import downsvg from '../../../assets/down.svg';
import smile from '../../../assets/speech/smile.svg';
const { Title } = Typography;
import { useDebounceCallback } from '../../../component/useDebounce';

function SpeechThirdPage() {
  const { chapterId } = useParams(); // 从 URL 中提取 chapterId
  const [sentences, setSentences] = useState([]);
  const [recordingStates, setRecordingStates] = useState({});
  const [scores, setScores] = useState({}); // 新增状态变量用于存储分数
  const [chapterInfo, setChapterInfo] = useState(null); // 新增状态变量
  const mediaRecordersRef = useRef({});
  const audioBlobsRef = useRef({});
  const navigate = useNavigate();
  // 从 Local Storage 中读取 userInfo
  const userInfoString = localStorage.getItem('userInfo');
  const userInfo = userInfoString ? JSON.parse(userInfoString) : null;
  const userId = userInfo ? userInfo.userId : null;
  const token = userInfo ? userInfo.token : null; // 从 userInfo 中提取 token

  useEffect(() => {
    async function fetchData() {
      try {
        // 合并前两个请求
        // eslint-disable-next-line no-empty-pattern
        const [] = await Promise.all([
          axios.all([
            axios.get(`/api/sentences/chapter/${chapterId}`),
            axios.get(`/api/chapters/${chapterId}`) // 假设这是获取章节信息的API
          ]).then(axios.spread((sentencesResponse, chapterResponse) => {
            if (sentencesResponse.data && sentencesResponse.data.code === 200 && Array.isArray(sentencesResponse.data.data)) {
              setSentences(sentencesResponse.data.data);
            } else {
              console.error('Unexpected data format or request failed for sentences:', sentencesResponse.data);
            }

            if (chapterResponse.data && chapterResponse.data.code === 200) {
              setChapterInfo(chapterResponse.data.data);
            } else {
              console.error('Unexpected data format or request failed for chapter info:', chapterResponse.data);
            }

            return [sentencesResponse, chapterResponse];
          }))
        ]);

        // 单独处理第三个请求
        const recordingsResponse = await axios.get(`/api/speech/user-chapter`, {
          params: { userId, chapterId },
          headers: { Authorization: `Bearer ${token}` } // 添加 token 到请求头
        });

        if (recordingsResponse.data && recordingsResponse.data.code === 200 && Array.isArray(recordingsResponse.data.data)) {
          console.log('User recordings response:', recordingsResponse.data); // 调试日志

          const initialScores = recordingsResponse.data.data.reduce((acc, cur) => {
            acc[cur.sentenceId] = cur.score;
            return acc;
          }, {});

          console.log('Initial scores:', initialScores); // 调试日志

          setScores(initialScores);
        } else {
          console.error('Unexpected data format or request failed for user recordings:', recordingsResponse.data);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    fetchData();
  }, [chapterId, userId, token]); // 确保 token 也在依赖数组中

  const handleRecordClick = (sentenceId) => {
    if (recordingStates[sentenceId]) {
      stopRecording(sentenceId);
    } else {
      startRecording(sentenceId);
    }
  };

  const startRecording = async (sentenceId) => {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mimeType = 'audio/webm'; // 使用 webm 格式

    mediaRecordersRef.current[sentenceId] = new MediaRecorder(stream, { mimeType });

    mediaRecordersRef.current[sentenceId].ondataavailable = event => {
      if (!mediaRecordersRef.current[sentenceId].audioChunks) {
        mediaRecordersRef.current[sentenceId].audioChunks = [];
      }
      mediaRecordersRef.current[sentenceId].audioChunks.push(event.data);
    };

    mediaRecordersRef.current[sentenceId].onstop = () => {
      const audioBlob = new Blob(mediaRecordersRef.current[sentenceId].audioChunks, { type: mimeType });
      const audioUrl = URL.createObjectURL(audioBlob);
      const audio = new Audio(audioUrl);
      audio.play();

      // 保存录音文件
      audioBlobsRef.current[sentenceId] = audioBlob;

      // 清空chunks数组，以便下一次录音
      mediaRecordersRef.current[sentenceId].audioChunks = [];

      // 发送录音文件和标准文本到后端
      sendRecordingToBackend(sentenceId, audioBlob);
    };

    mediaRecordersRef.current[sentenceId].start();
    setRecordingStates(prevStates => ({ ...prevStates, [sentenceId]: true }));
  };

  const stopRecording = (sentenceId) => {
    if (mediaRecordersRef.current[sentenceId]) {
      mediaRecordersRef.current[sentenceId].stop();
      setRecordingStates(prevStates => ({ ...prevStates, [sentenceId]: false }));
    }
  };

  const sendRecordingToBackend = async (sentenceId, audioBlob) => {
    const formData = new FormData();
  
    // Append the audio blob with a proper file name
    formData.append('file', audioBlob, 'recording.webm'); // 使用 .webm 扩展名
    formData.append('referenceText', sentences.find(sentence => sentence.sentenceId === sentenceId)?.englishText);
    formData.append('userId', userId);
    formData.append('sentenceId', sentenceId);
    formData.append('chapterId', chapterId); // 添加 chapterId 参数
  
    try {
      // Make POST request to backend
      const response = await axios.post('/api/speech/recognize', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${token}`
        }
      });

      if (response.data && response.data.score !== undefined) { // 检查是否有 score 属性
        console.log('Recording submitted successfully:', response.data);
        // 更新分数
        setScores(prevScores => ({
          ...prevScores,
          [sentenceId]: response.data.score
        }));
      } else {
        console.error('Unexpected data format or request failed for recording submission:', response.data);
      }
    } catch (error) {
      console.error('Error submitting recording:', error);
    }
  };

  const playAudio = (audioBase64) => {
    const audioElement = new Audio(`data:audio/mpeg;base64,${audioBase64}`);
    audioElement.play();
  };

  // 从当前哈希路径中提取 bookId 或 bookTitle
  const hashPath = window.location.hash;
  const pathParts = hashPath.split('/');
  const bookIdOrTitle = pathParts[2]; 

  const handleGoBack = (event) => {
    event.preventDefault(); // 阻止默认的链接行为
    window.history.back(); // 返回上一页
};

  const handleToResult = () => {
    navigate(`/dialogue/${bookIdOrTitle}/chapter/${chapterId}/report`);
  };

  const getScoreColor = (score) => {
    if (score === undefined) {
      return '#888'; // 灰色
    } else if (score >= 60) {
      return '#2db7f5'; // 绿色
    } else {
      return '#ff4d4f'; // 红色
    }
  };
  // 使用防抖 Hook 包装 handleLogin 和 handleVerificationLogin
  const debouncedPlayAudio = useDebounceCallback(playAudio, 500, [playAudio]);
  const debouncedhandleRecordClick = useDebounceCallback(handleRecordClick,500,[handleRecordClick]);

  return (
    <div className="SpeechThirdPage">
      <Button icon={<LeftOutlined />} type="primary" onClick={handleGoBack} style={{ width:100,display: 'flex', alignItems: 'center', color:'#23153C',background:'white',marginLeft:30,marginTop:30 }}>
        <span style={{ marginLeft: 3 }}>返回</span>
      </Button>
      <Title level={3}>{chapterInfo ? chapterInfo.title : 'Loading...'}</Title>
      <Title level={5}>{chapterInfo ? chapterInfo.etitle : 'Loading...'}</Title>
      <div style={{ marginTop: 16 }}>
        {Array.isArray(sentences) && sentences.length > 0 ? (
          sentences.map((sentence) => (
            <Card
              key={sentence.sentenceId}
              style={{
                marginTop: 16,
                backgroundColor: '#ffffff',
                padding: '16px'
              }}
            >
              <div className="sentence-container">
                <div className="text-container">
                  <Typography.Text strong style={{ display: 'block', marginBottom: 8, fontSize: '18px' }}>{sentence.englishText}</Typography.Text>
                  <Typography.Text style={{ display: 'block' }}>{sentence.chineseText}</Typography.Text>
                </div>
                <div className="button-container">
                  {/* 播放标准录音按钮 */}
                  <Button 
                    type="primary"
                    shape="circle"
                    icon={<CustomerServiceOutlined />}
                    style={{ backgroundColor: '#23153C', borderColor: '#23153C', marginRight: '16px' }}
                    onClick={() => debouncedPlayAudio(sentence.audio)}
                  >
                  </Button>
                  {/* 开始录音按钮 */}
                  <Button
                    type="primary"
                    shape="circle"
                    icon={<AudioOutlined />}
                    style={{ backgroundColor: recordingStates[sentence.sentenceId] ? '#ff4d4f' : '#23153C', borderColor: recordingStates[sentence.sentenceId] ? '#ff4d4f' : '#23153C' }}
                    onClick={() => debouncedhandleRecordClick(sentence.sentenceId)}
                  >
                  </Button>
                </div>
                <div className="score-container">
                  <Typography.Text style={{fontSize: '16px', color: getScoreColor(scores[sentence.sentenceId]) }}>
                    Score：{scores[sentence.sentenceId] !== undefined ? scores[sentence.sentenceId] : 'Null'}
                  </Typography.Text>
                </div>
              </div>
            </Card>
          ))
        ) : (
          <p>No sentences found.</p>
        )}
        <div>
          <div className="t-container">
            <img src={smile} alt="SVG Image" className="smile-svg-image"></img>
            <img src={downsvg} alt="SVG Image" className="down-svg-image"></img>
            <p className='myp' onClick={handleToResult}>Complete And Get The Report</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default SpeechThirdPage;